import React, { useState } from 'react';
import { Form, Button, message, Checkbox } from 'antd';
import CommonLoading from '@/components/CommonLoading';
import CommonModal from '@/components/CommonModal';
import CommonTable from '@/components/CommonTable';
import FuzzyQueryStore from '@/components/FuzzyQueryStore'
import FuzzyQueryGoods from '@/components/FuzzyQueryGoods'
import { cloneDeep, isEmpty } from 'lodash';
import { getzjfstoreList, getSpecList, addGoodsOperator } from '../service';
import styles from '../index.module.less'


export default ({ visible, handleOk, handleCancel }) => {

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState([])
  const [storeId, setStoreId] = useState(undefined)//选中供应商id
  const [hasSize, setHas] = useState(true)
  const [allChecked, setAllChecked] = useState(false)//全选状态

  // 检索聚合
  const onFinish = async (value) => {
    if(loading){
      return
    }
    setLoading(true)
    const {data={}, success} = await getSpecList(value)
    if(success){
      const addDataSource = [];
      const bool = data['-'] ? false : true;
        Object.keys(data).forEach(item=>{//尺码
          const sizeStage=data[item]
          const colorArr=[]
          Object.keys(sizeStage).forEach(items=>{//颜色
            const colorStage=sizeStage[items],goodsArr=[]
            colorStage.map((child,index,_self)=>{
              goodsArr.push(child)
            })
            colorArr.push({
              color:items,
              goodsArr,
              colorChecked:false
            })
          })
          addDataSource.push({
            size:item,
            sizeChecked: false,
            colorArr
          })
        })
      // console.log(addDataSource,'addDataSource')
      setData(addDataSource)
      setHas(bool)
    }
    let timer = setTimeout(() => {
      setLoading(false);
      clearTimeout(timer);
      timer = null;
    }, 300)
  };
  
  // 真正添加商品
  const addGoods = async () => {
    if(loading){
      return
    }
    if (data.length) {
      const arr=[]
      data.map(item=>{
          item.colorArr.map(items=>{
            if(items.colorChecked){
              items.goodsArr.map(child=>{
                arr.push({...child})
              })
            }
          })
      })
      if (arr.length) {
        setLoading(true)
        const res=await addGoodsOperator(arr)
        if(res.success){
          message.success('添加商品成功')
          handleOk()
          onCancel()
        }
        let timer = setTimeout(() => {
          setLoading(false);
          clearTimeout(timer);
          timer = null;
        }, 300)
      } else {
        message.info('请选择尺寸，颜色');
      }
    } else {
      message.info('暂不支持该操作，请先检索供应商商品');
    }
  };

  //尺码规格
  const changeSize = (checked, index) => {
    const addDataSource=cloneDeep(data)
    addDataSource[index].sizeChecked=checked
    const newArr=[]
    addDataSource[index].colorArr.map((item,index,_self)=>{
      newArr.push({
        ...item,
        colorChecked:checked
      })
    })
    addDataSource[index].colorArr=newArr
    setData(addDataSource)
    const size_no=addDataSource.some(item=>item.sizeChecked==false)
    if(size_no){
      setAllChecked(false)
    }else{
      setAllChecked(true)
    }
  };

  //颜色
  const changeColor = (checked, index, indexs) => {
    const addDataSource=cloneDeep(data)
    addDataSource[index].colorArr[indexs].colorChecked=checked
    if(checked){
     const color_no= addDataSource[index].colorArr.some(item=>item.colorChecked==false)
      if(color_no){
        addDataSource[index].sizeChecked=false
        setAllChecked(false)
      }else{
        addDataSource[index].sizeChecked=true
        const size_no=addDataSource.some(item=>item.sizeChecked==false)
        if(size_no){
          setAllChecked(false)
        }else{
          setAllChecked(true)
        }
      }
    }else{
      addDataSource[index].sizeChecked=false
      setAllChecked(false)
    }
    setData(addDataSource)
  }

  //全选反全选
  const changeAllChecked = (checked) => {
    const addDataSource=cloneDeep(data)
    addDataSource.map(item=>{
         item.sizeChecked=checked
         item.colorArr.map(items=>{
           items.colorChecked=checked
         })
    })
    setData(addDataSource)
    setAllChecked(checked)
  };

  const columns1 = [
    {
      title: (
        <>
          <Checkbox 
            onChange={(e) => changeAllChecked(e.target.checked)}
            checked={allChecked}
            disabled={isEmpty(data)} 
            className={styles.marginRight10}
          />
          尺码/规格
        </>
      ),
      dataIndex: 'size',
      key: 'size',
      width: 220,
      render: (text, {sizeChecked},index) => {
        return ( <>
          <Checkbox
            onChange={(e) => changeSize(e.target.checked,index)}
            checked={sizeChecked}
            className={styles.marginRight10}
          />
         {text}
        </>)
      },
    },
    {
      title: '颜色',
      dataIndex: 'colorArr',
      key: 'colorArr',
      width: 480,
      render:(text,{colorArr=[]},index)=>{
       return <div style={{display:"flex",flexWrap: "wrap"}}>
         {colorArr.map((item,indexs)=>{
         return <span key={item.color}>
             <Checkbox
                checked={item.colorChecked}
                style={{marginRight:24}}
                onChange={(e) => changeColor(e.target.checked,index,indexs)}
              >
                {item.color}
              </Checkbox>
             </span>})}
         </div>
      }
    },
  ];

  const columns2 = [
    {
      title: (
      <>
      <Checkbox 
        onChange={(e) => changeAllChecked(e.target.checked)}
        checked={allChecked}
        disabled={isEmpty(data)}
        className={styles.marginRight10}
      />
      颜色
      </>
      ),
      dataIndex: 'color',
      key: 'color',
      width: 300,
      render:(text,{colorArr=[]},index)=>{
        return <div style={{display:"flex",flexWrap: "wrap"}}>
          {colorArr.map((item,indexs)=>{
          return <Checkbox
                  checked={item.colorChecked}
                  style={{marginRight:24}}
                  onChange={(e) => changeColor(e.target.checked,index,indexs)}
                  key={item.color}
                 >
                   {item.color}
               </Checkbox>
             })}
          </div>
       }
    },
  ];

  //表格props 双形态
  const addTableProps = {
    data,
    columns: hasSize ? columns1 : columns2,
    scroll: { y: 480 },
  };

  //供应商改变
  const changeStore = (id) =>{
    setStoreId(id)
    setData([])
    form.resetFields(['goodsCommonId'])
  }

  //重置操作
  const addModalReset = () => {
    setStoreId(undefined)
    setData([])
    setHas(true)
    setAllChecked(false)
    form.resetFields()
  };

  //弹窗取消操作
  const onCancel = () =>{
    form.resetFields()
    handleCancel()
    setStoreId(undefined)
    setData([])
    setAllChecked(false)
  }

  return (
    <>
    <CommonModal
      title="添加商品"
      visible={visible}
      onCancel={onCancel}
      width="800px"
      footer={
        <>
          <Button onClick={onCancel}>取消</Button>
          <Button type="primary" onClick={addGoods}>添加商品</Button>
        </>
      }
    >
      <Form layout={'inline'} form={form} onFinish={onFinish} initialValues={{}} style={{marginBottom:16}} name='addModalForm'>
        <Form.Item label="供应商" name="zjfStoreId" rules={[{ required: true }]}>
          <FuzzyQueryStore width={200} onChange={(e)=>changeStore(e)} queryData={getzjfstoreList}/>
        </Form.Item>

        <Form.Item label="商品" name="goodsCommonId" rules={[{ required: true }]}>
            <FuzzyQueryGoods  width={250} storeId={storeId} type="spu" />
        </Form.Item>

        <Form.Item>
          <Button htmlType="submit" type="primary">查询</Button>&nbsp;&nbsp;
          <Button onClick={() => addModalReset()}>重置</Button>
        </Form.Item>
      </Form>
      <CommonTable {...addTableProps} />
    </CommonModal>
   <CommonLoading loading={loading} />
  </>
  );
};
